package cn.com.dev;

import cn.com.elite.Util;
import com.wisdge.dataservice.xhr.XHRPoolService;
import com.wisdge.utils.security.MD5;
import net.sf.json.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * @Title: cn.com.dev-uploadFile
 * @Description:ngsapitask-dbc 系统API接口开发Demo，重点关注业务逻辑部分
 * @Author: lijun
 * @Date 2021-12-07 14:22
 */
public class uploadFile {
    private static final Log log = LogFactory.getLog(uploadFile.class);
    private static XHRPoolService service = new XHRPoolService();

    public static void main(String[] args) throws Exception {

        String uploadResult = Util.uploadFile("http://127.0.0.1:8081/ngs/fs/upload_", "E:\\123.txt", "/headimg", getNameWithoutSuffix("123.txt"), "",getAuthToken());
        System.out.println(uploadResult);
    }

    public static String getNameWithoutSuffix(String filename)
    {
        try
        {
            if ((filename != null) && (filename.length() > 0)) {
                int dot = filename.lastIndexOf(".");
                if ((dot > -1) && (dot < filename.length()))
                    return filename.substring(0, dot);
            }
        }
        catch (Exception e) {
           e.printStackTrace();
        }
        return filename;
    }

    public static String getAuthToken() {
        String token = "";
        try
        {
            String payload = "{\"appId\":\"elite.ngs\", \"appSecret\":\"Letmein_0308\"}";
            log.debug("payload:" + payload);
            String key = MD5.encrypt(payload + "elite.nsg");
            Map heads = new HashMap();
            heads.put("key", key);
            String result = service.post("http://127.0.0.1:8081/ngs/fs/auth", payload, "application/json; charset=utf-8", heads);
            log.debug("result:" + result);
            JSONObject json = JSONObject.fromObject(result);
            String code = json.getString("code");
            if (code.equals("1"))
                token = json.getString("value");
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        log.debug("token:" + token);
        return token;
    }
}
